<template>
  <div class="data-container">
    <!-- 顶部标题和切换按钮 -->
    <div class="header">
      <div class="header-left">
        <h1>健康数据统计</h1>
      </div>
      <div class="view-switch">
        <el-radio-group v-model="viewType" @change="handleViewChange">
          <el-radio-button label="1">按天查看</el-radio-button>
          <el-radio-button label="2">按周查看</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 数据展示区域 -->
    <div class="data-content">
      <!-- 按天展示 -->
      <template v-if="viewType === '1'">
        <div class="search-bar">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="datePickerOptions"
            @change="handleDateRangeChange">
          </el-date-picker>
          <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
          <el-button @click="handleReset" style="margin-left: 10px">重置</el-button>
        </div>
        <div class="data-grid">
          <div v-for="(item, index) in dailyData" :key="index" class="data-card">
            <div class="card-header">
              <div class="date-info">
                <span class="date">{{ item.date }}</span>
                <span class="create-time">{{ formatDate(item.createTime) }}</span>
              </div>
              <el-button type="text" @click="viewDailyReport(item)">查看报告</el-button>
            </div>
            <div class="card-content">
              <div class="data-item">
                <span class="label">步数</span>
                <span class="value">{{ item.stepNumber }}步</span>
              </div>
              <div class="data-item">
                <span class="label">饮水量</span>
                <span class="value">{{ item.waterVolume }}L</span>
              </div>
              <div class="data-item">
                <span class="label">睡眠时长</span>
                <span class="value">{{ item.timeSubHour }}小时{{ item.timeSubMinutes >= 10 ? item.timeSubMinutes : `0${item.timeSubMinutes}` }}分钟</span>
              </div>
              <div class="data-item">
                <span class="label">血压</span>
                <span class="value">{{ item.sbp }}/{{ item.dbp }} mmHg</span>
              </div>
              <div class="data-item">
                <span class="label">体重</span>
                <span class="value">{{ item.weightDiff }} kg</span>
              </div>
              <div class="data-item">
                <span class="label">连续记录</span>
                <span class="value">{{ item.continuousDays }} 天</span>
              </div>
              <div class="data-item">
                <span class="label">睡眠质量</span>
                <div class="sleep-quality">
                  <span>深睡: {{ item.deepSleepPercentage }}%</span>
                  <span>浅睡: {{ item.lightSleepPercentage }}%</span>
                  <span>REM: {{ item.remSleepPercentage }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- 按周展示 -->
      <template v-else>
        <div class="week-container">
          <div class="week-header">
            <el-date-picker
              v-model="selectedWeek"
              type="week"
              format="yyyy 第 WW 周"
              placeholder="选择周"
              :picker-options="pickerOptions"
              @change="handleWeekChange">
            </el-date-picker>
            <el-button 
              type="primary" 
              @click="viewWeeklyReport"
              style="margin-left: 20px">
              查看报告
            </el-button>
          </div>
          
          <div class="date-range-info" v-if="selectedWeek">
            <span>数据日期范围：{{ getDateRange() }}</span>
          </div>
          
          <div class="week-data">
            <div v-for="(item, index) in weekData.records" :key="index" class="week-item">
              <div class="week-item-header">
                <div class="date-info">
                  <span class="week-day">{{ formatWeekDay(item.createTime) }}</span>
                  <span class="week-date">{{ formatDate(item.createTime) }}</span>
                </div>
                <div class="record-info">
                  <span class="continuous-days">连续记录 {{ item.continuousDays }} 天</span>
                </div>
              </div>
              <div class="week-item-content">
                <div class="data-row">
                  <span class="label">步数</span>
                  <span class="value">{{ item.stepNumber }}步</span>
                </div>
                <div class="data-row">
                  <span class="label">饮水量</span>
                  <span class="value">{{ item.waterVolume }}L</span>
                </div>
                <div class="data-row">
                  <span class="label">睡眠时长</span>
                  <span class="value">{{ calculateSleepDuration(item) }}</span>
                </div>
                <div class="data-row">
                  <span class="label">血压</span>
                  <span class="value">{{ item.sbp }}/{{ item.dbp }} mmHg</span>
                </div>
                <div class="data-row">
                  <span class="label">体重</span>
                  <span class="value">{{ item.weightDiff }} kg</span>
                </div>
                <div class="data-row sleep-quality-row">
                  <span class="label">睡眠质量</span>
                  <div class="sleep-quality">
                    <span>深睡: {{ item.deepSleepPercentage }}%</span>
                    <span>浅睡: {{ item.lightSleepPercentage }}%</span>
                    <span>REM: {{ item.remSleepPercentage }}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 分页器 -->
    <div class="pagination" v-if="viewType === '1'">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 返回顶部按钮 -->
    <el-backtop :bottom="100">
      <div class="backtop">
        <i class="el-icon-caret-top"></i>
      </div>
    </el-backtop>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'HealthData',
  data() {
    return {
      viewType: '1', // 1-按天，2-按周
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dailyData: [], // 按天数据
      weeklyData: [], // 按周数据
      selectedWeek: null, // 选择的周
      weekData: [], // 周数据
      dateRange: [], // 日期范围
      datePickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const now = new Date()
          // 获取本周一的日期
          const monday = new Date(now)
          monday.setDate(now.getDate() - now.getDay() + 1)
          monday.setHours(0, 0, 0, 0)
          // 禁用本周及之后的日期
          return time.getTime() >= monday.getTime()
        },
        firstDayOfWeek: 1 // 设置周一为一周的第一天
      }
    }
  },
  created() {
    this.fetchData()
    // 设置默认选择上一周
    const lastWeek = new Date()
    lastWeek.setDate(lastWeek.getDate() - 7)
    this.selectedWeek = lastWeek
  },
  methods: {
    // 获取数据
    fetchData() {
      if (this.viewType === '1') {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        
        // 添加日期范围参数
        if (this.dateRange && this.dateRange.length === 2) {
          params.beginTime = this.dateRange[0]
          params.endTime = this.dateRange[1]
        }
        
        request({
          url: `gather/user/${this.viewType}`,
          method: 'get',
          params
        }).then(res => {
          this.dailyData = res.data.records
          this.total = res.data.total
        })
      } else {
        this.fetchWeekData()
      }
    },
    // 获取周数据
    fetchWeekData() {
      if (!this.selectedWeek) return
      
      const startDate = new Date(this.selectedWeek)
      startDate.setDate(startDate.getDate() - startDate.getDay() + 1) // 设置为周一
      
      // 格式化为 yyyy-MM-dd 格式的北京时间
      const year = startDate.getFullYear()
      const month = String(startDate.getMonth() + 1).padStart(2, '0')
      const day = String(startDate.getDate()).padStart(2, '0')
      const formattedDate = `${year}-${month}-${day}`
      
      request({
        url: `gather/user/${this.viewType}`,
        method: 'get',
        params: {
          zondDate: formattedDate,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        this.weekData = res.data
      })
    },
    // 切换视图类型
    handleViewChange() {
      this.currentPage = 1
      if (this.viewType === '2') {
        this.fetchWeekData()
      } else {
        this.fetchData()
      }
    },
    // 周选择器变化
    handleWeekChange() {
      this.fetchWeekData()
    },
    // 查看日报
    viewDailyReport(item) {
      this.$router.push({
        path: '/reportDay',
        query: {
          id: item.id
        }
      })
    },
    // 查看周报
    viewWeeklyReport() {
      if (!this.selectedWeek) return
      
      const startDate = new Date(this.selectedWeek)
      startDate.setDate(startDate.getDate() - startDate.getDay() + 1) // 设置为周一
      
      // 格式化为 yyyy-MM-dd 格式的北京时间
      const year = startDate.getFullYear()
      const month = String(startDate.getMonth() + 1).padStart(2, '0')
      const day = String(startDate.getDate()).padStart(2, '0')
      const formattedDate = `${year}-${month}-${day}`
      
      this.$router.push({
        path: '/reportWeek',
        query: {
          startDate: formattedDate
        }
      })
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 计算睡眠时长
    calculateSleepDuration(item) {
      if (!item.sleepTime || !item.wakeupTime) return '--'
      const sleepTime = new Date(item.sleepTime)
      const wakeupTime = new Date(item.wakeupTime)
      const diff = wakeupTime - sleepTime
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      return `${hours}小时${minutes >= 10 ? minutes : `0${minutes}`}分钟`
    },
    // 格式化星期几
    formatWeekDay(date) {
      if (!date) return ''
      const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const day = new Date(date).getDay()
      return weekDays[day]
    },
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    },
    // 获取日期范围
    getDateRange() {
      if (!this.selectedWeek) return ''
      const startDate = new Date(this.selectedWeek)
      startDate.setDate(startDate.getDate() - startDate.getDay() + 1) // 设置为周一
      
      const endDate = new Date(startDate)
      endDate.setDate(startDate.getDate() + 6) // 设置为周日
      
      return `${this.formatDate(startDate)} 至 ${this.formatDate(endDate)}`
    },
    // 处理日期范围变化
    handleDateRangeChange() {
      this.currentPage = 1
      this.fetchData()
    },
    // 处理查询
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    // 处理重置
    handleReset() {
      this.dateRange = []
      this.currentPage = 1
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.data-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.data-content {
  margin-bottom: 20px;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.data-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
  }
  
  .date-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  
  .card-header .date {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  
  .card-header .create-time {
    font-size: 12px;
    color: #909399;
  }
  
  .card-content {
    padding: 15px;
  }
  
  .data-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .data-item:last-child {
    margin-bottom: 0;
  }
  
  .data-item .label {
    color: #606266;
    font-size: 14px;
  }
  
  .data-item .value {
    color: #303133;
    font-weight: 500;
  }
  
  .sleep-quality {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  
  .sleep-quality span {
    font-size: 12px;
    color: #606266;
  }
}

.week-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.week-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.date-range-info {
  text-align: center;
  margin: 15px 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
}

.week-data {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.week-item {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.week-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  
  .date-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  
  .week-day {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  
  .week-date {
    font-size: 14px;
    color: #909399;
  }
  
  .record-info {
    .continuous-days {
      font-size: 12px;
      color: #67c23a;
      background: rgba(103, 194, 58, 0.1);
      padding: 4px 8px;
      border-radius: 4px;
    }
  }
}

.data-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
  
  .label {
    color: #606266;
    font-size: 14px;
  }
  
  .value {
    color: #303133;
    font-weight: 500;
    font-size: 14px;
  }
}

.sleep-quality-row {
  margin-bottom: 0;
  
  .sleep-quality {
    display: flex;
    flex-direction: column;
    gap: 4px;
    text-align: right;
    
    span {
      font-size: 12px;
      color: #606266;
    }
  }
}

.backtop {
  height: 100%;
  width: 100%;
  background-color: #f2f5f6;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
  text-align: center;
  line-height: 40px;
  color: #1989fa;
  border-radius: 4px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

@media (max-width: 768px) {
  .data-grid {
    grid-template-columns: 1fr;
  }
  
  .week-data {
    grid-template-columns: 1fr;
  }
}
</style>